package org.execute.tool.虚拟币;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TronBalance{
    private static final OkHttpClient client = new OkHttpClient();

    public static double getTRXBalance(String address) throws Exception {
        String url = "https://api.trongrid.io/v1/accounts/" + address;
        Request request = new Request.Builder().url(url).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new Exception("请求失败: " + response.code());

            String jsonStr = response.body().string();
            JSONObject json = JSON.parseObject(jsonStr);
            JSONArray data = json.getJSONArray("data");
            if (data.isEmpty()) return 0.0;

            JSONObject account = data.getJSONObject(0);
            long balanceSun = account.getLongValue("balance");
            return balanceSun / 1_000_000.0;
        }
    }

    public static void main(String[] args) throws Exception {
        String address = "TA1fCrU4DtvzhAryb8GA7QSfCDq6KxiGGg";
        double balance = getTRXBalance(address);
        System.out.println("TRX 余额: " + balance + " TRX");
    }
}
